package com.itboye.core.object;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.itboye.baidu.util.TipsToast;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.alert.LoadingDialog;
import com.itboye.jmsfhz.R;
import com.itboye.jmsfhz.app.MainApplication;

/**
 * @author hebidu     2016-4-25  wushunhui修改版
 * 继承该类不需要自己寻找控件，不需要自己写oncreate(),只需要重写里面的抽象方法即可
 */
@SuppressLint("NewApi") public abstract class BaseActivity extends FragmentActivity {

	public static final String EVENT_TYPE_UNKNOWN = BaseActivity.class.getName()+"_unknown";
	View statusBar;
	private static TipsToast tipsToast;
	LoadingDialog progressDialog = null;
	@SuppressLint("ResourceAsColor") @Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(initView());//设置布局
		progressDialog = new LoadingDialog();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			Window window = getWindow();
			// Translucent status bar
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

			statusBar = new View(this);
			ViewGroup.LayoutParams param = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
					getStatusBarHeight());
			statusBar.setLayoutParams(param);
//			setStatusBarColor(R.color.main_color);
			this.addContentView(statusBar, param);
			
			//App.getInstance().addActivity(this);
			
		}
		//判断当前SDK版本号，如果是4.4以上，就是支持沉浸式状态栏的
				if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
		            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		        }
		smartInject();//自动获取控件
		onMyCreate();
	}
	public ResultEntity handlerErrorEntity(Object data) {
		ResultEntity result = (ResultEntity) data;
		if (result == null) {
			result = new ResultEntity("-1", "数据格式错误!~", data);
			return result;
		}

		if (result.hasError()) {

			if (result.getMsg().contains("java.net.UnknownHostException")) {
				ByAlert.alert("请连接网络 ");
			} else {
				ByAlert.alert("请连接网络 ");
			}
			result.setEventType(EVENT_TYPE_UNKNOWN);
			return result;
		}

		return result;
	}
	/*
	 * 判断网络连接是否已开
	 * true 已打开  false 未打开
	 * */
	public static boolean isConn(Context context){
		boolean bisConnFlag=false;
		ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo network = conManager.getActiveNetworkInfo();
		if(network!=null){
			bisConnFlag=conManager.getActiveNetworkInfo().isAvailable();
		}
		return bisConnFlag;
	}

	/**
	 * 当判断当前手机没有网络时选择是否打开网络设置
	 * @param context
	 */
	public static void showNoNetWorkDlg(final Context context) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setIcon(R.drawable.ic_launcher)         //
				.setTitle(R.string.app_name)            //
				.setMessage("当前无网络").setPositiveButton("设置", new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 跳转到系统的网络设置界面
						Intent intent = null;
						// 先判断当前系统版本
						if(android.os.Build.VERSION.SDK_INT > 10){  // 3.0以上
							intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
						}else{
							intent = new Intent();
							intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");
						}
						context.startActivity(intent);
						
					}
				}).setNegativeButton("知道了", null).show();
	}
	public static void showTips(int iconResId, String tips) {
		// TODO Auto-generated method stub
		if (tipsToast != null) {
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
				tipsToast.cancel();
			}
		} else {
			tipsToast = TipsToast.makeText(MainApplication.context,
					tips, TipsToast.LENGTH_SHORT);
		}
		tipsToast.show();
		tipsToast.setIcon(iconResId);
		tipsToast.setText(tips);
	}
	
	protected int getStatusBarHeight() {
		int result = 0;
		int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			result = getResources().getDimensionPixelSize(resourceId);
		}
		return result;
	}
	/**
	 * @param data
	 * @return 
	 * 2016-4-23 hebidu
	 */
	public ResultEntity handlerError(Object data) {
		ResultEntity  result = (ResultEntity) data;
		if(result == null){
			result = new ResultEntity("-1", "数据格式错误!~",data);
			return result;
		}
		
		if(result.hasError()){
			ByAlert.alert(result.getMsg());
			result.setEventType(EVENT_TYPE_UNKNOWN);
			return result;
		}
		
		return result;
	}
	
	/**
	 * 设置状态栏颜色，
	 * 
	 * @param color  颜色资源id， 如 R.color.orange</br>
	 *            0 黑色
	 */
	protected void setStatusBarColor(int color) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			if (color == 0) {
				statusBar.setBackgroundColor(Color.BLACK);
			} else {
				statusBar.setBackgroundColor(getResources().getColor(color));
			}

		}
	}

	/**
	 * @param 
	 * 2016-4-25 wushunhui
	 */
		private void smartInject() {

			try {
				Class<? extends Activity> clz = getClass();

				while (clz != BaseActivity.class) {

					Field[] fs = clz.getDeclaredFields();
					Resources res = getResources();
					String packageName = getPackageName();
					System.out.println("packageName" + packageName);
					for (Field field : fs) {

						System.out.println("field.getType()" + field.getType());
						if (!View.class.isAssignableFrom(field.getType())) {
							continue;
						}
						System.out.println("field.getName()" + field.getName());

						int viewId = res.getIdentifier(field.getName(), "id",
								packageName);
						System.out.println("viewId" + viewId);
						if (viewId == 0)
							continue;
						field.setAccessible(true);
						try {
							View v = findViewById(viewId);
							field.set(this, v);
							Class<?> c = field.getType();
							Method m = c.getMethod("setOnClickListener",
									android.view.View.OnClickListener.class);
							m.invoke(v, this);
						} catch (Throwable e) {
						}
						field.setAccessible(false);

					}

					clz = (Class<? extends Activity>) clz.getSuperclass();

				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		/**   
		 * @author liutiantian
		* 返回当前程序版本名   
		*/    
		public static String getAppVersionName(Context context) {    
		    String versionName = ""; 
		    String vsersionNmae="";
		    try {    
		        // ---get the package info---    
		        PackageManager pm = context.getPackageManager();    
		        PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);    
		        versionName = pi.versionName;  
		        
		        if (versionName == null || versionName.length() <= 0) {    
		            return "";    
		        }    
		    } catch (Exception e) {    
		        Log.e("VersionInfo", "Exception", e);    
		    }    
		    return versionName;    
		} 

		
		
		/***
		 * 所有继承BaseActivity所要调用的方法
		 * @return
		 */
		public abstract int initView();//初始化控件及其他

		public abstract void onMyCreate();//初始化数据相当于oncreate
		
		/**
		 * 显示进度对话框,带有消息 flag 是否可以取消
		 */
		@SuppressLint("NewApi")
		public void showProgressDialog(String message, boolean flag) {
			if (progressDialog == null)
				return;
			setProgressDialogMessage(message);

			progressDialog.show(getFragmentManager(), message);
			progressDialog.setCancelable(flag);

		}

		/**
		 * 设置进度对话框消息
		 * 
		 * @param message
		 */
		public void setProgressDialogMessage(String message) {
			progressDialog.setMsg(message);
		}

		/**
		 * 关闭进度对话框
		 */
		@SuppressLint("NewApi")
		public void closeProgressDialog() {
			if (progressDialog != null) {
				if (progressDialog.getDialog().isShowing()) {
					progressDialog.dismiss();
				}
			}
		}
		
}
